import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Popover, Tag, Button, Modal, message, List } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './MemberTag.less';

const FormItem = Form.Item;
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, title, val, loading } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const onCancel = () => {
    handleModalVisible(false);
    form.resetFields();
  };

  return (
    <Modal
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      confirmLoading={loading}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="标签名" style={{ display: 'none' }}>
        {form.getFieldDecorator('labelType', {
          initialValue: 0,
        })(<Input placeholder="请输入" />)
        }
      </FormItem>
      {val ?
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="标签名" style={{ display: 'none' }}>
          {form.getFieldDecorator('labelId', {
            initialValue: val ? val.labelId : null,
          })(<Input placeholder="请输入" />)
          }
        </FormItem>
        :
        null
      }
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="标签名">

        {form.getFieldDecorator('labelName', {
          initialValue: val ? val.labelName : null,
          rules: [{ required: true, message: '标签名不能为空' }],
        })(<Input placeholder="请输入" maxLength={8} />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ tag, loading }) => ({
  tagList: tag.tagList,
  loading: loading.models.tag,
}))
@Form.create()
export default class MemberTag extends PureComponent {
  state = {
    modalVisible: false,
    modalTitle: '',
    modalValue: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tag/fetchTagList',
      payload: { labelType: 0 }
    });
  }

  _handleSearch() {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        labelType: 0,
      };

      dispatch({
        type: 'tag/fetchTagList',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalTitle: '添加',
      modalValue: '',
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    console.log('fieldsfieldsfieldsfields??', fields)
    const { dispatch } = this.props;
    if (fields.labelId) {
      this.props.dispatch({
        type: 'tag/editTag',
        payload: fields,
        callback: () => this._handleSearch()
      });
    } else {
      dispatch({
        type: 'tag/addTag',
        payload: fields,
        callback: () => this._handleSearch()
      });
    }

    this.setState({
      modalVisible: false,
    });
  };

  deleteTag(labelId) {
    Modal.confirm({
      iconType: 'exclamation-circle',
      title: '确定要删除此标签吗？',
      okText: "确定",
      cancelText: "取消",
      onCancel: () => { },
      onOk: () => {
        this.props.dispatch({
          type: 'tag/deleteTag',
          payload: { labelId: labelId, },
          callback: () => this._handleSearch()
        });
      },
    });
  };

  editTag = item => {
    console.log(item)
    this.setState({
      modalTitle: '编辑',
      modalValue: item,
      modalVisible: true,
    });
  };

  renderForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 12, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem label="标签名称">
              {getFieldDecorator('labelName', {})(<Input placeholder="请输入标签名" />)}
            </FormItem>

          </Col>
          <Button type="primary" htmlType="submit" onClick={() => this._handleSearch()} >
            查询
        </Button>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      tagList,
      loading,
    } = this.props;
    const { modalVisible, modalTitle, modalValue } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                添加
              </Button>
            </div>
          </div>
        </Card>
        <List
          rowKey="id"
          style={{ backgroundColor: '#fff', marginTop: 16, paddingTop: 16 }}
          loading={loading}
          grid={{ gutter: 16, xs: 1, sm: 2, md: 4, lg: 4, xl: 6, xxl: 6 }}
          dataSource={tagList}
          renderItem={item => (
            <List.Item>
              <Popover
                content={
                  <Button.Group>
                    <Button type="default" onClick={this.editTag.bind(this, item)} icon="edit" />
                    <Button type="danger" onClick={() => this.deleteTag(item.labelId)} icon="close-circle" />
                  </Button.Group>
                }
              >
                <Tag className={styles.tag}>{item.labelName}</Tag>
              </Popover>
            </List.Item>
          )}
        />
        <CreateForm
          {...parentMethods}
          title={modalTitle}
          val={this.state.modalValue}
          modalVisible={modalVisible}
          loading={this.props.loading}
        />
      </PageHeaderLayout>
    );
  }
}
